package com.aliyun.messagemgt.web.aop;

import com.alibaba.fastjson.JSON;
import com.aliyun.messagemgt.common.dto.base.UserInfo;
import com.aliyun.messagemgt.domain.repository.FouraRepository;
import com.aliyun.messagemgt.entities.foura.FourAUserResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IDEA
 * 用户信息注入AOP
 * <p>
 * 2020年6月5日 4A改造IDaaS
 *
 * @author:zhangxingxing 0027012120
 * @date:2019/3/15
 * @time:17:37
 */
@ConditionalOnProperty(name = "gts.enterprise.foura.enable",havingValue = "true")
@Configuration
@Aspect
@Order(5)
public class UserInfoAop {

    private static final Logger logger = LoggerFactory.getLogger(UserInfoAop.class);
    @Autowired
    private FouraRepository fouraRepository;


    /**
     * 切点为所有controller包下方法,包括4Acontroller
     * &&!execution(public * com.iwhalecloud.mgtcenter.controller.FourAController.*(..))
     */
//    @Pointcut("execution(public * com.iwhalecloud.mgtcenter.controller..*(..)) && !execution(public * com.iwhalecloud.mgtcenter.controller.IDaaSController.*(..))")
    @Pointcut("execution(public * com.aliyun.messagemgt.web.controller..*(..)) && !execution(public * com.aliyun.messagemgt.web.controller.push..*(..))")
    public void userInfoPoint() {

    }

    @Before("userInfoPoint()")
    public void before(JoinPoint joinPoint) {
        logger.info("add userInfo");

        Object[] params = joinPoint.getArgs();
        //遍历获取参数实体
        UserInfo userInfo = null;
        for (Object param : params) {
            if (param instanceof UserInfo) {
                userInfo = (UserInfo) param;
                break;
            }
        }
        if(userInfo == null){
            logger.error("{} 参数未按要求继承UserInfo", joinPoint.getSignature());
            return;
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        FourAUserResponse extUser = (FourAUserResponse) fouraRepository.getUserAndExtUserCode(request).get("datas");
        if (extUser != null) {
            //设置userInfo
            userInfo.setUserName(extUser.getUserName());
            userInfo.setUserId(extUser.getUserId());
            /*
             * 在这里兼容之前的逻辑，全部设置为管理员角色，实际用户角色权限通过4A控制
             * 4A权限配置：
             *      普通用户：配置除去“我的待办”以外的资源
             *      管理员：配置所有资源
             */
            userInfo.setDepartment(extUser.getOrgCode());
            userInfo.setDepartmentName(extUser.getDepartmentName());
            userInfo.setRole(1);
//            userInfo.setRole(iDaaSUserSession.getRole());
//            if (iDaaSUserSession.getDepartment() != null) {
//                userInfo.setDepartment(iDaaSUserSession.getDepartment());
//            }
//            if (iDaaSUserSession.getDepartmentName() != null) {
//                userInfo.setDepartmentName(iDaaSUserSession.getDepartmentName());
//            }
            //本地启动
//            userInfo.setUserName("测试").setUserId("1").setRole(1);
        } else {
            logger.error("未获取到登陆session的UserInfo：{}", joinPoint.getSignature());
            return;
        }

        logger.info("获取用户权限信息 {}", JSON.toJSONString(userInfo));
    }
}
